﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using TemplateWeb.Helpers;

namespace TemplateWeb
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private Object thisLock = new Object();

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            Application["OnlineUsers"] = 0;
            Application["count_visit"] = 0;
        }

        protected void Session_Start()
        {
            // Code that runs when a new session is started    
            Application.Lock();
            Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
            Application.UnLock();
            int count_visit = 0;

            //Kiểm tra file count_visit.txt nếu không tồn tại thì         
            if (!System.IO.File.Exists(Server.MapPath("/Content/Count/count_visit.txt")))
            {
                count_visit = 1;
            }
            // Ngược lại thì      
            else
            {
                // Đọc dử liều từ file count_visit.txt    
                System.IO.StreamReader read = new System.IO.StreamReader(Server.MapPath("/Content/Count/count_visit.txt"));
                count_visit = int.Parse(read.ReadLine());
                read.Close();
                // Tăng biến count_visit thêm 1      
                count_visit+=10;

                // khóa website         
                Application.Lock();

                // gán biến Application count_visit     
                Application["count_visit"] = count_visit;

                // Mở khóa website    
                Application.UnLock();

                lock (thisLock)
                {
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(Server.MapPath("/Content/Count/count_visit.txt"));
                    writer.WriteLine(count_visit);
                    writer.Close();
                }
            }
        }

        protected void Session_End()
        {
            Application.Lock();
            Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
            Application.UnLock();
        }
    }
}